#!/usr/bin/env python
# -*- coding:utf-8 -*-
# projectname: pythoncode
# author: lzf time:2022/5/28
# name : 012 购物系统

# 用户类
# 属性    名字，密码，余额
# 行为
# 购物--->购买什么东西，购买多少     余额减少   商品库存减少

# 商品类
# 属性     类别，名字，单价，库存


# 定义用户类
class User():
    user = {}
    def __init__(self,username,passwd,money):
        self.username = username
        self.passwd = passwd
        self.money = money
        self.shopping_car = {}


    def buy_goods(self, goods, weight):
        if weight > Good.goodlist[goods].store:
            print("库存不足！")
        else:
            pay = weight*Good.goodlist[goods].price
            if self.money > pay:
                self.money -= pay
                Good.goodlist[goods].store -= weight

                print(f"购买成功，{self.username}剩余{self.money}元,"
                      f"{Good.goodlist[goods].good_name}剩余库存{Good.goodlist[goods].store}")
            else:
                print("余额不足")
    def register(self, newname, newpasswd, newmoeny):
        newuser = User(newname, newpasswd, newmoeny)
        newdict = {newname:newuser}
        User.user.update(newdict)
        print(f"有所已存在的用户：{User.user.keys()}")

    def login(self, newname, newpasswd):
        if not newname or not newpasswd:
            print("用户名或密码不能为空")
            return False
        if newname not in list(self.user.keys()):
            print("没有此用户")
            return False
        # 验证密码
        if User.user[newname].passwd != newpasswd:
            print("密码错误")
            return False
        # 登录
        print("登录成功！")
        return True


# 定义一个商品类
class Good(object):
    # 存放商品  {商品名：商品实例}
    goodlist = {}
    def __init__(self,category,good_name,price,store):
        self.category = category
        self.good_name = good_name
        self.price = price
        self.store = store
    def addgoods(self, category, good_name, price, store):
        newgood = Good(category, good_name, price, store)
        newdict = {good_name:newgood}
        Good.goodlist.update(newdict)

if __name__ == '__main__':
    user1 = User.register(User,"lzf", "123456", 5000)
    user2 = User.register(User,"qt", "123", 3000)

    apple = Good.addgoods(Good, "fruits", "苹果", 8, 30)
    beef = Good.addgoods(Good,"meat", "牛肉", 50, 20)
    def show_goods():
        for key in Good.goodlist:
            print(
                f"{Good.goodlist[key].category}\t{Good.goodlist[key].good_name}\t\t{Good.goodlist[key].price}\t\t{Good.goodlist[key].store}")
    def show_shopping_car(username):
        print("分类\t\t\t商品\t\t\t价格\t\t\t购买数量")
        for key,value in User.user[username].shopping_car.items():
            print(f"{value[0]}\t\t{value[1]}\t\t{value[2]}\t\t{value[3]}")

    username = None
    while True:
        print("欢迎来到三乐购物系统~".center(60,'*'))
        print("登录".center(50, ' '))
        print("注册".center(50, ' '))
        option = input("请选择你的操作：")
        if option.strip() == '注册':
            print("欢迎来到三乐注册界面~".center(40, ' '))
            username = input('请输入你注册的姓名：')
            passwd = input('请输入你注册的密码：')
            money = input('请输入你的初始金额：')
            User.register(User,username.strip(),passwd.strip(),int(money.strip()))
            print("注册成功！！".center(50,'^'))
        elif option.strip() == '登录':
            print("欢迎来到三乐登陆界面~".center(40, ' '))
            username = input("请输入你的用户名：")
            passwd = input("请输入你的密码：")
                # User.login(User, username, passwd)
            if User.login(User,username,passwd):
                break
            else:
                continue
        else:
            print("输入不合法！")
    while True:
        print("""
            1 --> 购买商品
            2 --> 查看购物车
            3 --> 结算订单
            4 --> 退出
            """)
        option = input("请输入你的选择：")
        # total_num = 0
        if option.strip() == '1':
            print("分类\t\t商品\t\t价格(元/斤)\t\t库存(斤)")
            show_goods()
            while True:
                select_good = input("请选择你要购买的商品：")
                select_num = input("请输入购买数量：")
                # print(username)
                if not select_num.isdigit() or not Good.goodlist.get(select_good,None):
                    print("输入不合法")
                else:
                    if Good.goodlist.get(select_good,None):
                        User.user[username].buy_goods(select_good.strip(),float(select_num))
                        good_in_shopping = User.user[username].shopping_car.get(select_good, None)
                        if good_in_shopping:
                            select_num += good_in_shopping[3]
                        # 加入购物车
                        User.user[username].shopping_car[select_good] = [Good.goodlist[select_good].category ,select_good.strip(), Good.goodlist[select_good].price, float(select_num)]
                        break
                    else:
                        print("没有你所购买的商品...")
                        break

            # User.user[username].shopping_car = {apple:[fruit,apple,num,store],pear:[frut,apple,num,price]}

        elif option.strip() == '2':
            show_shopping_car(username)
        # 结算清单
        elif option.strip() == '3':
            print("接下来为您结算订单...")
            print("分类\t\t商品\t\t价格\t\t库存")
            for key, value in User.user[username].shopping_car.items():
                print(f"{value[0]}\t\t{value[1]}\t\t{value[2]}\t\t{value[3]}")
            total = 0
            for i in User.user[username].shopping_car:
                total += User.user[username].shopping_car[i][2]*User.user[username].shopping_car[i][3]
            print(f"总计：{total}元")
            print(f"余额：{User.user[username].money}元")
            print('欢迎下次光临，祝您生活愉快！'.center(50, '*'))
            break
        elif option.strip() == '4' or option.strip().lower() == 'exit':
            break
        else:
            print("请输入正确的选择...")
